package com.jprocms.module.cms.framework.seq;


import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author jprocms
 */
public class IdBuilder {

    private Integer start;
    private AtomicInteger current;
    private Integer end;

    public IdBuilder() {

    }

    public IdBuilder(Integer start, Integer end) {
        if (start <= 0 || end <= 0 || start > end) {
            throw new RuntimeException("不合法的参数");
        }
        this.start = start;
        this.end = end;
        current = new AtomicInteger(start);
    }

    public Integer getStart() {
        return start;
    }

    public void setStart(Integer start) {
        this.start = start;
    }

    public Integer getEnd() {
        return end;
    }

    public void setEnd(Integer end) {
        this.end = end;
    }

    public Integer nextId() {
        if (start == null || end == null) {
            throw new RuntimeException("未初始化的id生成器");
        }
        if (start > end) {
            throw new RuntimeException("不合法的参数");
        }
        if (current == null) {
            current = new AtomicInteger(start);
        }
        if (current.get() > end) {
            throw new RuntimeException("id存储字段已耗尽");
        }
        return current.getAndAdd(1);
    }

}
